// 游戏配置
const GameSettings = {
    // 红灯绿灯停设置
    redLight: {
        greenLightMin: 4,
        greenLightMax: 7,
        redLightMin: 2,
        redLightMax: 4
    },
    // 一二三木头人设置
    woodman: {
        moveTimeMin: 3,
        moveTimeMax: 6,
        countdownInterval: 2,
        turnWaitTime: 2.5
    },
    // AI难度设置
    ai: {
        speed: 'normal',
        reactionProbability: 50
    }
};

// 游戏状态管理
class GameState {
    constructor() {
        this.currentScreen = 'start';
        this.gameMode = null;
        this.isPlaying = false;
        this.isPaused = false;
        this.round = 1;
        this.timeElapsed = 0;
        this.players = [];
        this.currentPlayer = null;
        this.gameMaster = null;
        this.currentCommand = 'waiting';
        this.moveCount = 0;
        this.startTime = null;
        this.timerInterval = null;
        this.gameLoopInterval = null;
    }

    reset() {
        this.round = 1;
        this.timeElapsed = 0;
        this.players = [];
        this.currentPlayer = null;
        this.currentCommand = 'waiting';
        this.moveCount = 0;
        this.startTime = null;
        this.isPlaying = false;
        this.isPaused = false;
        this.clearIntervals();
    }

    clearIntervals() {
        if (this.timerInterval) {
            clearInterval(this.timerInterval);
            this.timerInterval = null;
        }
        if (this.gameLoopInterval) {
            clearInterval(this.gameLoopInterval);
            this.gameLoopInterval = null;
        }
    }
}

// 玩家类
class Player {
    constructor(id, name, position = 0, isCurrentPlayer = false) {
        this.id = id;
        this.name = name;
        this.position = position;
        this.isCurrentPlayer = isCurrentPlayer;
        this.isEliminated = false;
        this.isMoving = false;
        this.emoji = isCurrentPlayer ? '🏃' : '👤';
        this.color = this.generateColor();
        this.speed = 1 + Math.random() * 0.5; // 随机速度差异
    }

    generateColor() {
        const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F'];
        return colors[Math.floor(Math.random() * colors.length)];
    }

    move(distance = 10) {
        if (!this.isEliminated) {
            this.position += distance * this.speed;
            this.isMoving = true;
            setTimeout(() => {
                this.isMoving = false;
            }, 300);
        }
    }

    stop() {
        this.isMoving = false;
    }

    eliminate() {
        this.isEliminated = true;
    }
}

// 游戏管理员类
class GameMaster {
    constructor() {
        this.isFacingAway = true;
        this.currentCount = 0;
        this.maxCount = 3;
        this.countdown = null;
    }

    startCounting() {
        this.currentCount = 0;
        return this.count();
    }

    count() {
        this.currentCount++;
        const isLast = this.currentCount >= this.maxCount;
        
        if (isLast) {
            this.isFacingAway = false;
            return { action: 'turn', count: this.currentCount };
        } else {
            return { action: 'count', count: this.currentCount };
        }
    }

    reset() {
        this.isFacingAway = true;
        this.currentCount = 0;
    }
}

// 游戏控制器
class GameController {
    constructor() {
        this.state = new GameState();
        this.gameCanvas = document.getElementById('gameCanvas');
        this.initEventListeners();
    }

    initEventListeners() {
        // 游戏模式选择
        document.querySelectorAll('.mode-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const mode = e.currentTarget.dataset.mode;
                this.startGame(mode);
            });
        });

        // 设置按钮
        document.getElementById('settingsBtn')?.addEventListener('click', () => this.showSettings());
        document.getElementById('backFromSettingsBtn')?.addEventListener('click', () => this.showScreen('start'));
        document.getElementById('saveSettingsBtn')?.addEventListener('click', () => this.saveSettings());
        document.getElementById('resetSettingsBtn')?.addEventListener('click', () => this.resetSettings());

        // 控制按钮
        document.getElementById('pauseBtn')?.addEventListener('click', () => this.togglePause());
        document.getElementById('restartBtn')?.addEventListener('click', () => this.restartGame());
        document.getElementById('menuBtn')?.addEventListener('click', () => this.showScreen('start'));
        document.getElementById('playAgainBtn')?.addEventListener('click', () => this.restartGame());
        document.getElementById('backToMenuBtn')?.addEventListener('click', () => this.showScreen('start'));

        // 移动控制（键盘）
        document.addEventListener('keydown', (e) => {
            if (this.state.isPlaying && !this.state.isPaused) {
                if (e.key === 'ArrowRight' || e.key === ' ') {
                    this.handlePlayerMove();
                }
            }
        });

        // 移动控制（移动端按钮）
        document.getElementById('moveBtn')?.addEventListener('click', () => {
            if (this.state.isPlaying && !this.state.isPaused) {
                this.handlePlayerMove();
            }
        });

        document.getElementById('stopBtn')?.addEventListener('click', () => {
            if (this.state.isPlaying && !this.state.isPaused) {
                this.handlePlayerStop();
            }
        });
    }

    showScreen(screenName) {
        document.querySelectorAll('.screen').forEach(screen => {
            screen.classList.remove('active');
        });
        document.getElementById(screenName + 'Screen').classList.add('active');
        this.state.currentScreen = screenName;
    }

    startGame(mode) {
        this.state.reset();
        this.state.gameMode = mode;
        this.state.startTime = Date.now();
        
        // 播放游戏开始音效
        if (typeof soundManager !== 'undefined') {
            soundManager.play('gameStart');
        }
        
        // 初始化玩家
        this.initializePlayers();
        
        // 初始化游戏管理员
        this.state.gameMaster = new GameMaster();
        
        // 切换到游戏界面
        this.showScreen('game');
        
        // 开始游戏
        this.state.isPlaying = true;
        this.startTimer();
        
        // 根据游戏模式启动不同的游戏逻辑
        if (mode === 'woodman') {
            this.startWoodmanGame();
        } else if (mode === 'redlight') {
            this.startRedLightGame();
        }
        
        this.updateUI();
    }

    initializePlayers() {
        const playerCount = 10;
        this.state.players = [];
        
        // 创建当前玩家
        const currentPlayer = new Player(0, '你', 0, true);
        this.state.players.push(currentPlayer);
        this.state.currentPlayer = currentPlayer;
        
        // 创建AI玩家
        const aiNames = ['小明', '小红', '小李', '小王', '小张', '小陈', '小刘', '小周', '小吴'];
        for (let i = 1; i < playerCount; i++) {
            const aiPlayer = new Player(i, aiNames[i - 1], 0, false);
            this.state.players.push(aiPlayer);
        }
        
        this.renderPlayers();
        this.updatePlayerList();
    }

    startTimer() {
        this.state.timerInterval = setInterval(() => {
            if (!this.state.isPaused) {
                this.state.timeElapsed++;
                this.updateTimerDisplay();
            }
        }, 1000);
    }

    updateTimerDisplay() {
        const minutes = Math.floor(this.state.timeElapsed / 60);
        const seconds = this.state.timeElapsed % 60;
        const display = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        document.getElementById('timeDisplay').textContent = display;
    }

    // 一二三木头人游戏逻辑
    startWoodmanGame() {
        this.updateStatus('游戏开始！', 'green');
        this.woodmanGameLoop();
    }

    woodmanGameLoop() {
        const settings = GameSettings.woodman;
        this.state.gameLoopInterval = setInterval(() => {
            if (this.state.isPaused) return;
            
            const result = this.state.gameMaster.startCounting();
            
            if (result.action === 'count') {
                this.updateCommand(`${result.count}...`, 'red');
                this.state.currentCommand = 'stop';
                if (typeof soundManager !== 'undefined') {
                    soundManager.play('countdown', result.count);
                }
                this.checkMovingPlayers();
                
                // AI玩家逻辑
                this.aiPlayerLogic();
                
            } else if (result.action === 'turn') {
                this.updateCommand('木头人！', 'red');
                this.state.currentCommand = 'stop';
                if (typeof soundManager !== 'undefined') {
                    soundManager.play('stop');
                }
                this.checkMovingPlayers();
                
                // 管理员背身后给玩家移动机会 - 使用设置中的时间参数
                setTimeout(() => {
                    if (!this.state.isPaused) {
                        this.state.gameMaster.reset();
                        this.updateCommand('前进！', 'green');
                        this.state.currentCommand = 'move';
                        this.aiPlayerLogic();
                        
                        // 下一轮 - 使用设置中的时间参数
                        const moveDuration = (settings.moveTimeMin * 1000) + Math.random() * ((settings.moveTimeMax - settings.moveTimeMin) * 1000);
                        setTimeout(() => {
                            if (this.state.isPlaying && !this.state.isPaused) {
                                this.woodmanGameLoop();
                            }
                        }, moveDuration);
                    }
                }, settings.turnWaitTime * 1000);
            }
        }, settings.countdownInterval * 1000);
    }

    // 红灯绿灯停游戏逻辑
    startRedLightGame() {
        this.updateStatus('游戏开始！', 'green');
        this.redLightGameLoop();
    }

    redLightGameLoop() {
        this.state.gameLoopInterval = setInterval(() => {
            if (this.state.isPaused) return;
            
            const isGreenLight = Math.random() > 0.4;
            
            if (isGreenLight) {
                this.updateCommand('绿灯！前进！', 'green');
                this.state.currentCommand = 'move';
            } else {
                this.updateCommand('红灯！停！', 'red');
                this.state.currentCommand = 'stop';
                if (typeof soundManager !== 'undefined') {
                    soundManager.play('stop');
                }
                this.checkMovingPlayers();
            }
            
            // AI玩家逻辑
            this.aiPlayerLogic();
            
            // 随机时长后切换信号 - 使用设置中的时间参数
            const settings = GameSettings.redLight;
            const duration = isGreenLight ? 
                (settings.greenLightMin * 1000) + Math.random() * ((settings.greenLightMax - settings.greenLightMin) * 1000) :
                (settings.redLightMin * 1000) + Math.random() * ((settings.redLightMax - settings.redLightMin) * 1000);
            
            setTimeout(() => {
                if (this.state.isPlaying && !this.state.isPaused) {
                    this.redLightGameLoop();
                }
            }, duration);
        }, 1000);
    }

    handlePlayerMove() {
        if (!this.state.currentPlayer || this.state.currentPlayer.isEliminated) return;
        
        if (this.state.gameMode === 'woodman') {
            if (this.state.currentCommand === 'move') {
                this.state.currentPlayer.move();
                this.state.moveCount++;
                if (typeof soundManager !== 'undefined') {
                    soundManager.play('move');
                }
                this.renderPlayers();
                this.checkWinCondition();
            }
        } else if (this.state.gameMode === 'redlight') {
            if (this.state.currentCommand === 'move') {
                this.state.currentPlayer.move();
                this.state.moveCount++;
                if (typeof soundManager !== 'undefined') {
                    soundManager.play('move');
                }
                this.renderPlayers();
                this.checkWinCondition();
            }
        }
    }

    handlePlayerStop() {
        if (this.state.currentPlayer) {
            this.state.currentPlayer.stop();
        }
    }

    // AI玩家逻辑
    aiPlayerLogic() {
        const settings = GameSettings.ai;
        this.state.players.forEach(player => {
            if (player.isCurrentPlayer || player.isEliminated) return;
            
            if (this.state.currentCommand === 'move') {
                // AI在可以移动时有概率移动 - 使用设置中的参数
                if (Math.random() < settings.reactionProbability / 100) {
                    const delay = 500 + Math.random() * 1500;
                    const distance = this.getAIDistance(settings.speed);
                    
                    setTimeout(() => {
                        player.move(distance);
                        this.renderPlayers();
                    }, delay);
                }
            }
        });
    }

    getAIDistance(speed) {
        switch (speed) {
            case 'slow':
                return 4 + Math.random() * 8;
            case 'normal':
                return 6 + Math.random() * 10;
            case 'fast':
                return 8 + Math.random() * 12;
            default:
                return 6 + Math.random() * 10;
        }
    }

    checkMovingPlayers() {
        // 检查在应该停止时仍在移动的玩家
        this.state.players.forEach(player => {
            if (player.isMoving && !player.isEliminated) {
                // 一定概率淘汰正在移动的玩家
                if (Math.random() < 0.8) {
                    player.eliminate();
                    this.showMessage(`${player.name} 被淘汰了！`);
                    if (typeof soundManager !== 'undefined') {
                        soundManager.play('eliminate');
                    }
                }
            }
        });
        
        this.renderPlayers();
        this.updatePlayerList();
        this.checkGameEnd();
    }

    checkWinCondition() {
        if (this.state.currentPlayer && this.state.currentPlayer.position >= 100) {
            this.endGame(true);
        }
    }

    checkGameEnd() {
        const alivePlayers = this.state.players.filter(p => !p.isEliminated);
        
        if (alivePlayers.length === 0) {
            this.endGame(false);
        } else if (alivePlayers.length === 1 && !alivePlayers[0].isCurrentPlayer) {
            this.endGame(false);
        }
    }

    endGame(isWin) {
        this.state.isPlaying = false;
        this.state.clearIntervals();
        
        // 计算最终排名
        const alivePlayers = this.state.players.filter(p => !p.isEliminated);
        const rank = alivePlayers.findIndex(p => p.isCurrentPlayer) + 1;
        
        // 更新结束界面
        const resultTitle = document.getElementById('resultTitle');
        if (isWin) {
            resultTitle.textContent = '🎉 胜利！';
            if (typeof soundManager !== 'undefined') {
                soundManager.play('win');
            }
        } else {
            resultTitle.textContent = '💀 游戏结束';
            if (typeof soundManager !== 'undefined') {
                soundManager.play('lose');
            }
        }
        
        document.getElementById('finalRank').textContent = `#${rank}`;
        document.getElementById('survivalTime').textContent = document.getElementById('timeDisplay').textContent;
        document.getElementById('moveCount').textContent = this.state.moveCount;
        
        // 显示结束界面
        setTimeout(() => {
            this.showScreen('end');
        }, 1000);
    }

    togglePause() {
        this.state.isPaused = !this.state.isPaused;
        const pauseBtn = document.getElementById('pauseBtn');
        pauseBtn.textContent = this.state.isPaused ? '▶️ 继续' : '⏸️ 暂停';
        
        if (this.state.isPaused) {
            this.updateStatus('游戏暂停', 'red');
        } else {
            this.updateStatus('游戏继续', 'green');
        }
    }

    restartGame() {
        if (this.state.gameMode) {
            this.startGame(this.state.gameMode);
        }
    }

    renderPlayers() {
        if (!this.gameCanvas) return;
        
        // 清空现有的玩家元素
        const existingPlayers = this.gameCanvas.querySelectorAll('.player, .game-master');
        existingPlayers.forEach(el => el.remove());
        
        // 渲染游戏管理员
        if (this.state.gameMaster) {
            const masterElement = document.createElement('div');
            masterElement.className = 'game-master';
            masterElement.textContent = '👁️';
            if (this.state.gameMaster.isFacingAway) {
                masterElement.classList.add('watching');
            } else {
                masterElement.classList.add('turned');
            }
            this.gameCanvas.appendChild(masterElement);
        }
        
        // 渲染玩家
        const canvasWidth = this.gameCanvas.offsetWidth;
        const canvasHeight = this.gameCanvas.offsetHeight;
        
        this.state.players.forEach(player => {
            const playerElement = document.createElement('div');
            playerElement.className = 'player';
            
            if (player.isCurrentPlayer) {
                playerElement.classList.add('current-player');
            }
            if (player.isEliminated) {
                playerElement.classList.add('eliminated');
            }
            if (player.isMoving) {
                playerElement.classList.add('moving');
            }
            
            // 计算位置
            const x = Math.min((player.position / 100) * (canvasWidth - 30), canvasWidth - 30);
            const y = canvasHeight - 60 - (this.state.players.indexOf(player) * 40);
            
            playerElement.style.left = x + 'px';
            playerElement.style.top = y + 'px';
            playerElement.style.backgroundColor = player.color;
            playerElement.textContent = player.emoji;
            
            this.gameCanvas.appendChild(playerElement);
        });
    }

    updatePlayerList() {
        const playerList = document.getElementById('playerList');
        if (!playerList) return;
        
        // 按位置排序
        const sortedPlayers = [...this.state.players].sort((a, b) => b.position - a.position);
        
        playerList.innerHTML = sortedPlayers.map((player, index) => `
            <div class="player-item ${player.isEliminated ? 'eliminated' : ''} ${player.isCurrentPlayer ? 'current-player' : ''}">
                <span class="player-position">#${index + 1}</span>
                <span>${player.name} ${player.emoji}</span>
                <span>${Math.floor(player.position)}%</span>
            </div>
        `).join('');
    }

    updateStatus(text, type = 'normal') {
        const statusText = document.getElementById('statusText');
        if (statusText) {
            statusText.textContent = text;
            statusText.style.color = type === 'green' ? '#4CAF50' : type === 'red' ? '#f44336' : '#fff';
        }
    }

    updateCommand(text, type) {
        const commandText = document.getElementById('commandText');
        if (commandText) {
            commandText.textContent = text;
            commandText.className = `command-text ${type}`;
        }
    }

    updateUI() {
        this.updateTimerDisplay();
        document.getElementById('playersDisplay').textContent = this.state.players.filter(p => !p.isEliminated).length;
        document.getElementById('roundDisplay').textContent = this.state.round;
        this.updatePlayerList();
    }

    showSettings() {
        this.showScreen('settings');
        this.loadSettingsToUI();
        this.setupSettingsListeners();
    }

    loadSettingsToUI() {
        // 红灯绿灯停设置
        document.getElementById('greenLightMin').value = GameSettings.redLight.greenLightMin;
        document.getElementById('greenLightMinValue').textContent = GameSettings.redLight.greenLightMin;
        
        document.getElementById('greenLightMax').value = GameSettings.redLight.greenLightMax;
        document.getElementById('greenLightMaxValue').textContent = GameSettings.redLight.greenLightMax;
        
        document.getElementById('redLightMin').value = GameSettings.redLight.redLightMin;
        document.getElementById('redLightMinValue').textContent = GameSettings.redLight.redLightMin;
        
        document.getElementById('redLightMax').value = GameSettings.redLight.redLightMax;
        document.getElementById('redLightMaxValue').textContent = GameSettings.redLight.redLightMax;

        // 一二三木头人设置
        document.getElementById('moveTimeMin').value = GameSettings.woodman.moveTimeMin;
        document.getElementById('moveTimeMinValue').textContent = GameSettings.woodman.moveTimeMin;
        
        document.getElementById('moveTimeMax').value = GameSettings.woodman.moveTimeMax;
        document.getElementById('moveTimeMaxValue').textContent = GameSettings.woodman.moveTimeMax;
        
        document.getElementById('countdownInterval').value = GameSettings.woodman.countdownInterval;
        document.getElementById('countdownIntervalValue').textContent = GameSettings.woodman.countdownInterval;
        
        document.getElementById('turnWaitTime').value = GameSettings.woodman.turnWaitTime;
        document.getElementById('turnWaitTimeValue').textContent = GameSettings.woodman.turnWaitTime;

        // AI难度设置
        document.getElementById('aiSpeed').value = GameSettings.ai.speed;
        document.getElementById('aiReaction').value = GameSettings.ai.reactionProbability;
        document.getElementById('aiReactionValue').textContent = GameSettings.ai.reactionProbability + '%';
    }

    setupSettingsListeners() {
        // 滑块值更新监听器
        const sliders = [
            'greenLightMin', 'greenLightMax', 'redLightMin', 'redLightMax',
            'moveTimeMin', 'moveTimeMax', 'countdownInterval', 'turnWaitTime', 'aiReaction'
        ];

        sliders.forEach(id => {
            const slider = document.getElementById(id);
            if (slider) {
                slider.addEventListener('input', (e) => {
                    const valueElement = document.getElementById(id + 'Value');
                    if (valueElement) {
                        let value = e.target.value;
                        if (id === 'aiReaction') {
                            value += '%';
                        }
                        valueElement.textContent = value;
                    }
                });
            }
        });
    }

    saveSettings() {
        // 保存红灯绿灯停设置
        GameSettings.redLight.greenLightMin = parseFloat(document.getElementById('greenLightMin').value);
        GameSettings.redLight.greenLightMax = parseFloat(document.getElementById('greenLightMax').value);
        GameSettings.redLight.redLightMin = parseFloat(document.getElementById('redLightMin').value);
        GameSettings.redLight.redLightMax = parseFloat(document.getElementById('redLightMax').value);

        // 保存一二三木头人设置
        GameSettings.woodman.moveTimeMin = parseFloat(document.getElementById('moveTimeMin').value);
        GameSettings.woodman.moveTimeMax = parseFloat(document.getElementById('moveTimeMax').value);
        GameSettings.woodman.countdownInterval = parseFloat(document.getElementById('countdownInterval').value);
        GameSettings.woodman.turnWaitTime = parseFloat(document.getElementById('turnWaitTime').value);

        // 保存AI难度设置
        GameSettings.ai.speed = document.getElementById('aiSpeed').value;
        GameSettings.ai.reactionProbability = parseInt(document.getElementById('aiReaction').value);

        // 保存到本地存储
        localStorage.setItem('gameSettings', JSON.stringify(GameSettings));

        this.showMessage('设置已保存！');
        setTimeout(() => {
            this.showScreen('start');
        }, 1500);
    }

    resetSettings() {
        // 重置为默认值
        GameSettings.redLight = { greenLightMin: 4, greenLightMax: 7, redLightMin: 2, redLightMax: 4 };
        GameSettings.woodman = { moveTimeMin: 3, moveTimeMax: 6, countdownInterval: 2, turnWaitTime: 2.5 };
        GameSettings.ai = { speed: 'normal', reactionProbability: 50 };

        localStorage.removeItem('gameSettings');
        this.loadSettingsToUI();
        this.showMessage('设置已重置为默认值！');
    }

    loadSettingsFromStorage() {
        const saved = localStorage.getItem('gameSettings');
        if (saved) {
            try {
                const settings = JSON.parse(saved);
                Object.assign(GameSettings, settings);
            } catch (e) {
                console.warn('Failed to load settings from storage:', e);
            }
        }
    }

    showMessage(message) {
        // 创建临时消息元素
        const messageEl = document.createElement('div');
        messageEl.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 20px 40px;
            border-radius: 10px;
            font-size: 1.2rem;
            z-index: 1000;
            animation: fadeInOut 2s ease-in-out;
        `;
        messageEl.textContent = message;
        
        // 添加动画样式
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeInOut {
                0% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
                50% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
                100% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
            }
        `;
        document.head.appendChild(style);
        
        document.body.appendChild(messageEl);
        
        setTimeout(() => {
            messageEl.remove();
            style.remove();
        }, 2000);
    }
}

// 初始化游戏
let gameController;

document.addEventListener('DOMContentLoaded', () => {
    // 加载保存的设置
    const tempController = new GameController();
    tempController.loadSettingsFromStorage();
    tempController = null;
    
    gameController = new GameController();
    
    // 窗口大小改变时重新渲染
    window.addEventListener('resize', () => {
        if (gameController.state.isPlaying) {
            gameController.renderPlayers();
        }
    });
    
    // 防止空格键滚动页面
    window.addEventListener('keydown', (e) => {
        if (e.key === ' ' && gameController.state.isPlaying) {
            e.preventDefault();
        }
    });
});